<template>
    <div id="searchtop">
        <nut-icon name="left" color="#c1ab96" @click="back"></nut-icon>
        <nut-searchbar v-model="searchValue" :clearable="true">
            <template v-slot:rightout>
                <div @click="getsearch">搜索</div>
            </template>
        </nut-searchbar>
    </div>
</template>

<script>
import { searchProduct } from "../api/product";
export default {
    name: "searchTop",
    data() {
        return {
            searchValue: "",
            searchList: JSON.parse(localStorage.getItem("search")) || [],
            // 存储搜索匹配的商品
            foundProductList: [],
        };
    },
    methods: {
        back() {
            // 返回上一级
            this.$router.back();
            // this.$router.go(-1);
            // console.log(this.$router);
        },
        async getsearch() {
            // 空格，不进行搜索
            if (!/\S/.test(this.searchValue)) return;

            // 先筛选，根据是否有结果跳转对应的页面
            const { data } = await searchProduct(this.searchValue);
            this.foundProductList = data.result.rows;
            // 在 vuex 中存放搜索结果商品数据
            this.$store.commit("setFoundProductList", this.foundProductList);
            if (this.foundProductList.length == 0) {
                // 无结果
                this.$router.push("/search/searchnotfound");
            } else {
                // 有结果
                this.$router.push("/search/searchfound");
            }
            // 存放历史搜索记录(不重复存放)
            if (this.searchList.includes(this.searchValue)) return;

            this.searchList.unshift(this.searchValue);
            this.searchValue = "";
            if (this.searchList.length > 8) {
                this.searchList.pop();
            }
            // 因为localStorage是window对象的方法
            localStorage.setItem("search", JSON.stringify(this.searchList));
        },
    },
};
</script>

<style lang="scss" scoped>
#searchtop {
    background-color: #eae9e5;
    width: 100%;
    height: 13.333vw;
    display: flex;
    .nut-icon:before {
        top: 122%;
        left: 97%;
    }
    .nut-searchbar {
        background-color: #eae9e5;
    }
    .nut-searchbar__search-input {
        background-color: #f2f2f2;
    }
    ::v-deep .nut-searchbar__right-search-icon {
        width: 14.667vw;
        height: 6.667vw;
        color: #f2f2f2;
        background-color: #c1ab96;
        border-radius: 4vw;
    }
}
</style>